function [k_out] = gen_k(vec_A, QQ, X_var, X_exp,const_var,data,dates0,lag,Ebar)
% Parameter
NQ = size(QQ,3);
eta = (X_var' - repmat(const_var,size(X_var,1),1)'-[vec_A(1:3*lag)';vec_A(3*lag+1:6*lag)';vec_A(6*lag + 1:9*lag)']*X_exp')';
OMEGA= cov(eta);
BB0=chol(OMEGA,'lower'); %Generate lower cholesy factorization of covariance matrix eta

dates5      = 1987 + 10/12;
dates7012   = 1970 + 12/12;
dateslehman = 2008 +  9/12;


%87 crash
index_87 = [find(abs(dates0 - dates5) < 10^(-5))];

% 1970
index_70 = [find(abs(dates0 -dates7012)<10^(-6))];

% Lehman Crash
index_lehman = [find(abs(dates0 -dateslehman)<10^(-6)):find(abs(dates0 -dateslehman)<10^(-6))];




e_store = NaN(NQ,size(Ebar,2));
for iii = 1:NQ
    
    % rotate and normalize B
    B_initial=BB0*QQ(:,:,iii);
    B_est=B_initial*diag(sign(diag(B_initial))); %normalize so that self-irfs are positive
    ehat = eta(:,:)*inv(B_est)';

    %============ Event constraint ==============
    %      Ebar(1)            Ebar(2)           Ebar(3)              Ebar(4)
    kkk = [ehat(index_87,3)   ehat(index_70,1)  ehat(index_lehman,3) ehat(index_lehman,1)];
    
   %B_store(:,:,iii) = B_est;
    e_store(iii,:) = kkk;
end


k_out = prctile(e_store,75);
end